package com.qf.limit.controller;


import com.qf.limit.commons.base.BaseController;
import com.qf.limit.commons.r.Codes;
import com.qf.limit.commons.r.R;
import com.qf.limit.commons.utils.CodesUtils;
import com.qf.limit.commons.utils.JwtUtils;
import com.qf.limit.entity.Friendrequest;
import com.qf.limit.entity.User;
import com.qf.limit.entity.vo.UserLoginVo;
import com.qf.limit.entity.vo.UserUpdatePasswordVo;
import com.qf.limit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;


/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2024-09-10 09:34:07
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController extends BaseController<UserService> {

    @PostMapping("/register")
    public R register(@RequestBody @Validated User user){
        System.out.println("用户注册-{}"+user);
        return R.succ(getBaserService().save(user));
    }


    /**
     * 修改密码
     * @param userUpdatePasswordVo
     * @return
     */
    @PostMapping("/updatePassword")
    public R updatePassword(@RequestBody @Validated UserUpdatePasswordVo userUpdatePasswordVo){
        log.debug("修改用户密码-[]",userUpdatePasswordVo);
        //判断验证码
        int inputCode = userUpdatePasswordVo.getCode();
        Integer creteCode = CodesUtils.getCode(userUpdatePasswordVo.getUsername());
        if (!Objects.equals(creteCode,inputCode)){
            //验证码不匹配
            return R.fail(Codes.CODE_ERROR);
        }
        //修改密码
        getBaserService().updateUserPassword(userUpdatePasswordVo.getUsername()
                ,userUpdatePasswordVo.getPassword());
        //删除验证码
        CodesUtils.remove(userUpdatePasswordVo.getUsername());
        return R.succ();
    }

    @PostMapping("/login")
    public R login(@RequestBody UserLoginVo userLoginVo){
        log.debug("[user login]用户登录-{}",userLoginVo);
        //查询用户信息
        User user = getBaserService().queryUsernameAndPassword(userLoginVo);
        if (user == null){
            return R.fail(Codes.LOGIN_FILL);
        }

        //用户的部分信息 -> 转换成jwt令牌中,返回给客户端
        String jwtToken = JwtUtils.createJwtToken()
                .add("id",user.getId())
                .add("nickname",user.getNickname())
                .add("header",user.getHeader())
                .build();

        return R.succ(jwtToken);
    }
    /**
     * 根据关键词搜索
     */
    @GetMapping({"/search/{keyword}","/search/"})
    public R search(@PathVariable(required = false) String keyword){
        log.debug("根据关键词搜索-{}",keyword);
        return R.succ(getBaserService().searchUserByKeyword(keyword));
    }


}

